<?php

class AccountController extends Frontend_Base_Controller
{

    public function init()
    {
        parent::init();
        $this->view->headTitle($this->view->translate('account_page_title'));
    }

    public function createAction()
    {

        if (Application_Model_Front_User::isLoggedIn())
        {

            $redirector = new Zend_Controller_Action_Helper_Redirector();
            $redirector->gotoUrl('/account/my')->redirectAndExit();

        }

        $this->view->headTitle($this->view->translate('account_create_page_title'));

        if ($this->getRequest()->isPost())
        {
            $request     = $this->getRequest();
            $posted_data = $request->getPost();

            // Email unique check
            if (!empty($posted_data['email']) && !empty($posted_data['is_unique']))
            {
                $mapper = new Application_Model_UserMapper();
                $model  = $mapper->findByEmail($posted_data['email']);
                echo $model ? '0' : '1';
                die();
            }

            // Login unique check
            if (!empty($posted_data['login']) && !empty($posted_data['is_unique']))
            {
                $mapper = new Application_Model_UserMapper();
                $model  = $mapper->findByLogin($posted_data['login']);
                echo $model ? '0' : '1';
                die();
            }

            $required_keys = array(
                'age',
                'country',
                'cpassword',
                'email',
                'firstname',
                'gender',
                'lastname',
                'password',
                'username',
            );

            $fields_valid = true;

            foreach ($required_keys as $key_name)
            {
                if (!isset($posted_data[$key_name]) || !is_scalar($posted_data[$key_name]))
                {
                    $fields_valid = false;
                    break;
                }
            }

            if ($fields_valid)
            {
                if (!filter_var($posted_data['email'], FILTER_VALIDATE_EMAIL))
                {
                    $fields_valid = false;
                }

                if ($posted_data['password'] != $posted_data['cpassword'])
                {
                    $fields_valid = false;
                }

                $mapper = new Application_Model_UserMapper();
                $model  = $mapper->findByLogin($posted_data['username']);
                if ($model)
                {
                    $fields_valid = false;
                }

                $mapper = new Application_Model_UserMapper();
                $model  = $mapper->findByEmail($posted_data['email']);
                if ($model)
                {
                    $fields_valid = false;
                }

                // Create account if fields happen to be valid
                if ($fields_valid)
                {

                    // Generate activation hash
                    $activation_hash = md5(uniqid() . $posted_data['email']);

                    // Assemble columns data array
                    $data = array(
                        'first_name'      => $posted_data['firstname'],
                        'last_name'       => $posted_data['lastname'],
                        'male'            => ($posted_data['gender'] == $this->view->translate('account_create_gender_male')),
                        'email'           => $posted_data['email'],
                        'age'             => $posted_data['age'],
                        'country'         => $posted_data['country'],
                        'login'           => $posted_data['username'],
                        'password'        => md5($posted_data['password']),
                        'activated'       => 0,
                        'activation_hash' => $activation_hash,
                    );

                    // Try to create DB record
                    $uid = $mapper->createFromArray($data);

                    if ($uid > 0)
                    {
                        // Send confirmation letter if DB record successfully created
                        $general_settings = Zend_Registry::get('general');
                        $mail_sender      = new Application_Model_Mail_Sender();
                        $mail_sender->selectTemplate('account_create_confirmation');
                        if ($mail_sender->hasTemplate())
                        {
                            $tokens                   = $data;
                            $tokens['app_name']       = $general_settings['name'];
                            $tokens['activation_url'] = $this->view->serverUrl() . $this->view->baseUrl() . $this->_helper->url('activate', 'account', null, array('hash' => $activation_hash));
                            $mail_sender->setTo($data['email']);
                            $mail_sender->setTokens($tokens);
                            $mail_sender->send();

                            echo '1';
                            die();
                        }

                    }
                }
                echo '0';
                die();
            }
        }
    }

    public function activateAction()
    {

        if (Application_Model_Front_User::isLoggedIn())
        {

            $redirector = new Zend_Controller_Action_Helper_Redirector();
            $redirector->gotoUrl('/account/my')->redirectAndExit();

        }

        $this->view->headTitle($this->view->translate('account_activate_page_title'));

        $request = $this->getRequest();
        $hash    = $request->getParam('hash');

        if ($this->getRequest()->isPost() && $hash)
        {

            $mapper = new Application_Model_UserMapper();
            if ($mapper->activateByHash($hash)) {
                echo '1';
            }

            die();
        }

    }

    public function loginAction()
    {

        if (Application_Model_Front_User::isLoggedIn())
        {

            $redirector = new Zend_Controller_Action_Helper_Redirector();
            $redirector->gotoUrl('/account/my')->redirectAndExit();

        }

        $old_token = false;
        $old_cpid  = false;
        $session   = Zend_Registry::get('session');
        $token     = md5(uniqid() . microtime());
        $captcha   = new Zend_Captcha_Figlet(array(
            'name'    => 'account_login_capcha',
            'wordLen' => 6,
            'timeout' => 300,
        ));

        if ($session->account_login_security_token)
        {
            $old_token = $session->account_login_security_token;
        }
        if ($session->account_login_captcha_id)
        {
            $old_cpid = $session->account_login_captcha_id;
        }

        $session->account_login_security_token = $token;
        $this->view->security_token            = $token;

        if ($this->_request->isXmlHttpRequest())
        {
            $request  = $this->getRequest();
            $email    = $request->getParam('access_login');
            $password = $request->getParam('access_password');
            $token    = $request->getParam('access_token');
            $ctext    = $request->getParam('captcha');
            $mapper   = new Application_Model_UserMapper();
            if ($email && $password && $token == $old_token && $captcha->isValid(array('id' => $old_cpid, 'input' => $ctext)))
            {
                $model = $mapper->loadByEmailAndPassword($email, md5($password));
                if ($model && Application_Model_Front_User::setModel($model))
                {
                    echo '1';
                    die();
                }
            }

            $session->account_login_captcha_id = $captcha->generate();
            $captcha_html                      = $captcha->render($this->view);
            echo json_encode(array(
                'success'      => 0,
                'token'        => $session->account_login_security_token,
                'captcha_html' => $captcha_html,
            ));
            die();
        }

        $session->account_login_captcha_id = $captcha->generate();
        $this->view->captcha               = $captcha;
        $this->view->headTitle($this->view->translate('account_login_page_title'));

    }

    public function myAction()
    {

        if (!Application_Model_Front_User::isLoggedIn())
        {
            $redirector = new Zend_Controller_Action_Helper_Redirector();
            $redirector->gotoUrl('/account/create')->redirectAndExit();
        }
        $this->view->headTitle($this->view->translate('account_my_page_title'));

    }

    public function logoutAction()
    {

        Application_Model_Front_User::destroyModel();
        $redirector = new Zend_Controller_Action_Helper_Redirector();
        $redirector->gotoUrl('/account/login')->redirectAndExit();

    }

    public function forgotAction()
    {

        if (Application_Model_Front_User::isLoggedIn())
        {
            $redirector = new Zend_Controller_Action_Helper_Redirector();
            $redirector->gotoUrl('/account/my')->redirectAndExit();
        }

        $request = $this->getRequest();
        $form    = new Application_Form_ForgotPassword();

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($request->getPost()))
            {

                $general_settings = Zend_Registry::get('general');
                $mapper           = new Application_Model_UserMapper();
                $form_values      = $form->getValues();
                $model            = $mapper->findByEmail($form_values['email']);

                if ($model)
                {
                    $mail_sender = new Application_Model_Mail_Sender();
                    $mail_sender->selectTemplate('password_reset_instructions');
                    $reset_password_hash = $mapper->createResetPasswordHash($model);

                    if ($mail_sender->hasTemplate() && $reset_password_hash)
                    {
                        $mail_sender->setTo($model->getEmail());
                        $mail_sender->setTokens(array(
                            'email'      => $form_values['email'],
                            'first_name' => $model->getFirstName(),
                            'last_name'  => $model->getLastName(),
                            'link_url'   => $this->view->serverUrl() . $this->view->baseUrl() . $this->_helper->url('preset', 'account', null, array('hash' => $reset_password_hash)),
                            'app_name'   => $general_settings['name'],
                        ));
                        $mail_sender->send();
                        $this->_helper->flashMessenger->addMessage(array('success' => $this->view->translate('password_reset_link_sent')));
                    }
                } else {
                    $this->_helper->flashMessenger->addMessage(array('error' => $this->view->translate('password_reset_email_not_found')));
                }

                return $this->_helper->redirector('forgot');
            }
        }

        $this->view->form = $form;
        $this->view->headTitle($this->view->translate('account_forgot_page_title'));
    }

    public function presetAction()
    {

        if (Application_Model_Front_User::isLoggedIn())
        {
            $redirector = new Zend_Controller_Action_Helper_Redirector();
            $redirector->gotoUrl('/account/my')->redirectAndExit();
        }

        $request = $this->getRequest();
        $hash    = $request->getParam('hash');
        $form    = new Application_Form_ResetPassword();
        $mapper  = new Application_Model_UserMapper();

        if ($hash)
        {

            $model = $mapper->findByResetPasswordHash($hash);
            if (!$model)
            {
                return $this->_helper->redirector('forgot');
            }

            if ($this->getRequest()->isPost())
            {
                if ($form->isValid($request->getPost()))
                {
                    $form_values = $form->getValues();
                    if ($form_values['password'])
                    {
                        $model->setPassword(md5($form_values['password']));
                        if ($mapper->save($model))
                        {
                            $mapper->clearResetPasswordHash($model);
                            $this->_helper->flashMessenger->addMessage(array('success' => $this->view->translate('password_change_success')));
                            $redirector = new Zend_Controller_Action_Helper_Redirector();
                            $redirector->gotoUrl('/account/login')->redirectAndExit();
                        }
                    }
                }
            }
        }
        $this->view->form = $form;
        $this->view->headTitle($this->view->translate('account_preset_page_title'));
    }

}

